//
//  EventsViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 6/10/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "EventsViewController.h"

#import "Constant.h"

#import "JsonClass.h"

#import "ParserClass.h"

#import "PostClass.h"

#import "EventViewTableViewCell.h"

#import "Events.h"

#import "UIManager.h"

#import "UserProfileViewController.h"

#import "IIViewDeckController.h"

#import "StarRatingView.h"

#import "Songs.h"

#import "FTWAPI.h"



#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

@interface EventsViewController (){
    
    FTWAPI *ftwapi;
    
}

@end

@implementation EventsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (!ftwapi) {
        ftwapi = [FTWAPI sharedInstance];
    }
    
    // Do any additional setup after loading the view from its nib.
    
//    UserProfileViewController *userProfView = [[UserProfileViewController alloc]init];
//    
//    IIViewDeckController* deckController =  [[IIViewDeckController alloc] initWithCenterViewController:self leftViewController:userProfView rightViewController:nil];
    
    
    
//    UIImage *buttonImage = [UIImage imageNamed:@"userProfile.png"];
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    [button setImage:buttonImage forState:UIControlStateNormal];
//    button.frame = CGRectMake(0, 100, buttonImage.size.width, buttonImage.size.height);
//    [button addTarget:self action:@selector(userProfile:) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.leftBarButtonItem = customBarItem;
    
    [self.navigationController.navigationBar setHidden:YES];
    
    self.activityLoader.hidden = NO;
//    
//    dispatch_async(kBgQueue, ^{
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            self.activityLoader.hidden = YES;
//            
//            NSData *data = [[PostClass sharedItems] getEvents:[UIDevice currentDevice].identifierForVendor.UUIDString];
//            
//            [self performSelectorOnMainThread:@selector(fetchedData:)
//                                   withObject:data waitUntilDone:YES];
//            
//            
//        });
//    });
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelFavorites" object:@"cancelFavorites"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"cancelEvents" object:nil];
    
    //NSData *data = [[PostClass sharedItems] getHomeData:[UIDevice currentDevice].identifierForVendor.UUIDString];
    // NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:artistUrl]];
    //4
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [[PostClass sharedItems] getEvents:[UIDevice currentDevice].identifierForVendor.UUIDString];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];


    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navEventsImg.png"] forBarMetrics:UIBarMetricsDefault];
    
    [self.tblEvents setBackgroundColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
    
    [self setupPullToRefresh];
    
}


-(void)setupPullToRefresh
{
    //[_refreshControll endRefreshing];
    
    //    _refreshControll = [[UIRefreshControl alloc] init];
    //    _refreshControll.tintColor = [UIColor whiteColor];
    //    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    //    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    //    //self.refreshControll = refresh;
    //    [self.tblView addSubview:_refreshControll];
    
    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = self.tblEvents;
    
    _refreshControll = [[UIRefreshControl alloc] init];
    _refreshControll.tintColor = [UIColor redColor];
    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = _refreshControll;
}

-(void)refreshTable{
    
    [self.tblEvents reloadData];
    
    
}


-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);
    
    [self.theConnection cancel];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark - TableView Setup

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    //#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return 1;
//}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //return [[[ParserClass sharedItems] events] count];
    
    return [[[ParserClass sharedItems] events] count];
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([_refreshControll isRefreshing]) {
        [_refreshControll endRefreshing];
    }

    
    static NSString *CellIdentifier = @"Cell";
    
    EventViewTableViewCell *cell = (EventViewTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EventViewTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    // Configure the cell...
    
    Events *event = [[ParserClass sharedItems] events][indexPath.row];
    
    [cell.lblEventName setText: [event eventName]];
    [cell.lblEventLoc setText:[event eventLocation]];
    [cell.lblEventDesc setText:[event eventDesc]];
    [cell.lblEventDate setText:[event eventDate]];
    //[cell setImageString:[event eventImage]];
    
    @autoreleasepool {
        
        
        [cell.imgEventBG setAlpha:0];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            NSString *imageUrl = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [event eventImage]];
            
            [ftwapi setupCoverImage:cell.imgEventBG withURL:imageUrl];
            [cell.actLoading setHidden:YES];
            [cell.imgEventBG setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
        
        //[self animationActivity];
    }

    
    

    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark - Method For Fetching Data;

-(IBAction)userProfile:(id)sender{
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}



- (void)fetchedData:(NSData *)responseData {
    
    NSDictionary *json = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[JsonClass jsonParser:responseData],@"EventsProp", nil];
    
    [[ParserClass sharedItems] events:json];
    
    [self.tblEvents reloadData];
    
    NSLog(@"Events = %@", json);
}

- (void)viewDidUnload{
    
   // self.tblEvents = nil;
    
    [super viewDidUnload];
    
    [[ParserClass sharedItems] emptyEvent];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        //NSDictionary *dicdata = [NSJSONSerialization JSONObjectWithData:_receivedData options:kNilOptions error:nil];
        
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            
            NSDictionary *json = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[JsonClass jsonParser:_receivedData],@"EventsProp", nil];
            
            [[ParserClass sharedItems] events:json];
            
            [self.tblEvents reloadData];
            
            NSLog(@"Events = %@", json);
            
            
        }
        
        
        NSLog(@"Finish");
    }
    
}

@end
